﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PBO.Data.Rnd
{
    public static class RandomHelper
    {
        #region pokemondata

        public static PokemonNature GetNature(Random random)
        {
            return (PokemonNature)random.Next(25);
        }

        #endregion

        #region tool

        public static T GetRandom<T>(this T[] array, Random random)
        {
            return array[random.Next(array.Length)];
        }

        /// <summary>
        /// 获取指定个数 不重复的随机数组
        /// </summary>
        public static IEnumerable<T> GetRandom<T>(this IEnumerable<T> array, Random random, int count)
        {
            int length = array.Count();
            var ids = Reshuffle(random, length, count);
            for (int i = 0; i < count; i++)
            {
                yield return array.ElementAt(ids[i]);
            }
        }

        /// <summary>
        /// 获取指定个数尽可能不重复的随机数组
        /// </summary>
        /// <param name="random">种子</param>
        /// <param name="length">数组长度</param>
        /// <param name="count">返回长度</param>
        /// <returns></returns>
        private static int[] Reshuffle(Random random, int length, int count)
        {
            var arr = new int[length];
            for (int i = 0; i < length; i++)
            {
                arr[i] = i;
            }

            var result = new int[count];
            int j = length - 1;
            int index, temp;

            for (int i = 0; i < count; i++)
            {
                index = random.Next(j + 1);
                result[i] = arr[index];

                temp = arr[j];
                arr[j] = arr[index];
                arr[index] = temp;

                if (j == 0)
                    j = length - 1;
                else j--;
            }
            return result;
        }

        #endregion
    }
}
